Skip to main content

lumen 跨域问题解决方法 二

步骤

  1. 新建一个中间件

在app/http/middlemare中新建一个CorsMiddleware.php

  1. 书写中间件内容
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => getenv('ACCESS_CONTROL_ALLOW_ORIGIN'),
'Access-Control-Allow-Methods' => getenv('ACCESS_CONTROL_ALLOW_METHODS'),
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];

if ($request->isMethod('OPTIONS')) {
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}

$response = $next($request);
foreach ($headers as $key => $value) {
$response->header($key, $value);
}

return $response;
}
}
  1. 在.env文件中自定义允许的请求头
#跨域请求参数
ACCESS_CONTROL_ALLOW_ORIGIN=*
ACCESS_CONTROL_ALLOW_METHODS='GET, POST, PUT, DELETE, OPTIONS'
  1. 然后在内核文件注册该中间件 【ps:在bootstrap中的app.php中把相应的注释去掉 并修改成现在这个新建的中间件就可以了】
$app->middleware([
App\Http\Middleware\CorsMiddleware::class
]);

请求页面代码:

<script src="jquery.js"></script>
<script>
$(document).ready(function(){

$.ajax({
type: "POST",//或者"POST"
url: "http://localhost:8000/api/login",//请求地址
data: {'phone':13522474350,'password':123},//传入后台的参数
// dataType: "JSONP",
success: function(data){
console.log(data);
}//回调函数,请求成功后执行的函数,data为后台传来的数据

});

});
</script>